﻿using AutoMapper;
using MediatR;
using MySqlX.XDevAPI.Common;
using ProductionLine.API.Application.Command.Plan.Write;
using ProductionLine.Domain.Plan;
using ProductionLine.ErrorCode;
using ProductionLine.Infrastructure.Implement;

namespace ProductionLine.API.Application.Handler.Plan.Write
{
    public class UpdatePlanHandler : IRequestHandler<UpdatePlanCommand, APIResult<int>>
    {
        DatabaseContext db;
        IMapper mapper;

        public UpdatePlanHandler(DatabaseContext db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        public Task<APIResult<int>> Handle(UpdatePlanCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res=new APIResult<int>();
            var list = db.SqlSugar.Queryable<PlanModel>().Where(x => x.PlanId == request.PlanId).First();
            if (list == null)
            {
                res.Code = APIEnum.Fail;
                res.Msg = "不存在";
                return Task.FromResult(res);
            }
            list = mapper.Map(request, list);
            int r = db.SqlSugar.Updateable(list).Where(it => it.PlanId==request.PlanId).ExecuteCommand();
            if (r > 0)
            {
                res.Msg = "生产计划编辑成功";
                res.Data = r;
                res.Code = APIEnum.Success;
            }
            else
            {
                res.Msg = "生产计划编辑失败";
                res.Data = r;
                res.Code = APIEnum.Fail;
            }
            return Task.FromResult(res);
        }
    }
}
